package com.sgy.netty.chat;

import com.sgy.netty.NettyClientHandler;
import com.sgy.netty.codec.MessageCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NettyChatClient {

    private String ip;
    private int port;

    public NettyChatClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup group = null;
        try {
            // 创建线程组
            group = new NioEventLoopGroup();

            // 创建客户端启动助手
            Bootstrap bootstrap = new Bootstrap();

            // 设置线程组
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)  // 设置客户端通道实现为nio
                    .handler(new ChannelInitializer<Channel>() {  // 创建一个通道初始化对象
                        @Override
                        public void initChannel(Channel channel) throws Exception {
                            // 添加编解码器
                            channel.pipeline().addLast(new StringDecoder());
                            channel.pipeline().addLast(new StringEncoder());

                            channel.pipeline().addLast(new NettyChatClientHandler());
                        }
                    });

            // 启动客户端，等待连接服务器，同时将异步改为同步
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
            Channel channel = channelFuture.channel();
            System.out.println("-----------" + channel.localAddress().toString().substring(1) + "----------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                // 向服务端发送消息
                channel.writeAndFlush(msg);
            }

            // 关闭通道和关闭连接池
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        NettyChatClient nettyChatClient = new NettyChatClient("127.0.0.1", 9998);
        nettyChatClient.run();
    }
}
